package com.honghu.villagepost.activity.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.Group;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.honghu.villagepost.MainActivity;
import com.honghu.villagepost.R;
import com.honghu.villagepost.activity.OrderDetailsActivity;
import com.honghu.villagepost.adapter.CatListAdapter;
import com.honghu.villagepost.base.BaseFragment;
import com.honghu.villagepost.dao.manager.DbManager;
import com.honghu.villagepost.entity.dao.GoodsEntity;
import com.honghu.villagepost.entity.dao.StoreEntity;
import com.honghu.villagepost.entity.event.CatRefreshEvent;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.wuhenzhizao.sku.utils.ScreenUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class CatListFragment extends BaseFragment implements View.OnClickListener {

    private static final int MODEL_SETTLE = 0;//结算模式
    private static final int MODEL_MANAGER = 1;//删除管理模式
    @BindView(R.id.common_toolbar)
    FrameLayout mToolbar;

    @BindView(R.id.tv_title)
    TextView mTvTitle;

    @BindView(R.id.smart_refresh)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.cats_rv)
    RecyclerView mCatListRv;

    @BindView(R.id.layout_empty)
    View mNoDataView;

    @BindView(R.id.tv_total_money)
    TextView mTotalMoney;

    @BindView(R.id.tv_sub_title)
    TextView mTvMenuManager;

    //底部结算展示
    @BindView(R.id.settle_gp)
    Group mSettleGp;

    //底部全选复选框
    @BindView(R.id.select_all_cb)
    TextView mSelectAllCb;

    @BindView(R.id.tv_delete)
    TextView mTvDelete;

    private TextView mTvCatNum;

    private TextView mTvTopManager;

    private CatListAdapter mCatListAdapter;

    private int mModel;

    @Override
    protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_cat_list, container, false);
        return contentView;
    }

    @Override
    protected void initData() {
        initView();
        getCatList();
    }

    /**
     * Desc:初始化view
     * <p>
     * Author: [李豫]
     * Date: 2021-07-15
     */
    private void initView() {
        int statusBarHeight = ScreenUtils.getStatusBarHeight(getActivity());
        mToolbar.setPadding(0, statusBarHeight, 0, 0);

        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getCatList();
            }
        });
        mCatListRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager l = (LinearLayoutManager) recyclerView.getLayoutManager();
                int mScrollP = l.findFirstVisibleItemPosition();
                if (mScrollP >= 1) {
                    mToolbar.setVisibility(View.VISIBLE);
                } else {
                    mToolbar.setVisibility(View.GONE);
                }
            }
        });
        mCatListRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mCatListAdapter = new CatListAdapter();
        mCatListAdapter.setOnCatListAdapterListener(new CatListAdapter.OnCatListAdapterListener() {
            @Override
            public void onItemClick(StoreEntity storeEntity, int position) {
                List<GoodsEntity> goodsList = storeEntity.getGoodsList();
                double totalPrice = 0;
                for (GoodsEntity goodsEntity : goodsList) {
                    if (goodsEntity.isSelect()) {
                        totalPrice += goodsEntity.getPrice();
                    }
                }

                mTotalMoney.setText(getString(R.string.price_format, totalPrice));
                mSelectAllCb.setSelected(false);
            }
        });

        View headView = getLayoutInflater().inflate(R.layout.adapter_cat_header, null, false);
        mTvCatNum = headView.findViewById(R.id.tv_cat_num);
        mTvTopManager = headView.findViewById(R.id.tv_manager);
        mTvTopManager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchModel();
            }
        });
        mCatListAdapter.addHeaderView(headView);
        mCatListRv.setAdapter(mCatListAdapter);

        getView().findViewById(R.id.tv_settle).setOnClickListener(this);
        mTvMenuManager.setOnClickListener(this);
        mTvDelete.setOnClickListener(this);

        mSelectAllCb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean selected = mSelectAllCb.isSelected();
                mSelectAllCb.setSelected(!selected);
                if (mCatListAdapter != null) {
                    mCatListAdapter.selectAll(!selected);
                }
            }
        });
    }

    private void switchModel() {
        if (mModel == MODEL_SETTLE) {
            mModel = MODEL_MANAGER;
        } else {
            mModel = MODEL_SETTLE;
        }
        if (mModel == MODEL_SETTLE) {
            mTvTopManager.setText("管理");
            mTvMenuManager.setText("管理");
            mSettleGp.setVisibility(View.VISIBLE);
            mSelectAllCb.setVisibility(View.GONE);
            mTvDelete.setVisibility(View.GONE);
            if (mCatListAdapter != null) {
                mCatListAdapter.selectAll(false);
            }
        } else {
            mTvTopManager.setText("完成");
            mTvMenuManager.setText("完成");
            mSettleGp.setVisibility(View.GONE);
            mSelectAllCb.setVisibility(View.VISIBLE);
            mTvDelete.setVisibility(View.VISIBLE);
        }
    }

    /**
     * Desc:获取购物车数据
     * <p>
     * Author: [李豫]
     * Date: 2021-07-15
     */
    private void getCatList() {
        List<StoreEntity> catShopList = DbManager.getInstance().getCatShopList();
        mRefreshLayout.finishRefresh();
        if (catShopList != null && catShopList.size() > 0) {
            mNoDataView.setVisibility(View.GONE);
            mCatListAdapter.setNewData(catShopList);
            int num = getGoodsListNum(catShopList);
            mTvCatNum.setText(String.format("(%d)", num));
            mTvTitle.setText(String.format("购物车(%d)", num));
        } else {
            mCatListAdapter.setNewData(new ArrayList<>());
            mNoDataView.setVisibility(View.VISIBLE);
            mTvCatNum.setText("(0)");
            mTvTitle.setText("购物车");
            mSelectAllCb.setSelected(false);
        }
    }

    private int getGoodsListNum(List<StoreEntity> catShopList) {
        int totalNum = 0;
        for (StoreEntity storeEntity : catShopList) {
            totalNum += storeEntity.getGoodsList().size();
        }
        return totalNum;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (getActivity() != null) {
                ((MainActivity) getActivity()).setStatusBarTintResource(R.color.transparent);
            }
        } else {
            if (getActivity() != null) {
                ((MainActivity) getActivity()).setStatusBarTintResource(R.color.colorPrimaryDark);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_settle) {
            onSettle();
        } else if (v.getId() == R.id.tv_delete) {
            onDelete();
        }
    }

    /**
     * Desc:删除购物车商品
     * <p>
     * Author: [李豫]
     * Date: 2021-07-16
     */
    private void onDelete() {
        List<StoreEntity> storeEntityList = mCatListAdapter.getData();
        for (StoreEntity storeEntity: storeEntityList) {
            List<GoodsEntity> goodsList = storeEntity.getGoodsList();
            for (GoodsEntity goodsEntity: goodsList) {
                if (goodsEntity.isSelect()){
                    DbManager.getInstance().deleteGoods(goodsEntity);
                }
            }
        }
        getCatList();
    }

    /**
     * Desc:结算
     * <p>
     * Author: [李豫]
     * Date: 2021-07-16
     */
    private void onSettle() {
        StoreEntity selectCatShop = mCatListAdapter.getSelectCatShop();
        if (selectCatShop != null) {
            List settleItemList = new ArrayList();
            List<GoodsEntity> goodsList = selectCatShop.getGoodsList();
            for (GoodsEntity goodsEntity : goodsList) {
                if (goodsEntity.isSelect()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("quantity", goodsEntity.getStockQuantity());
                    map.put("skuId", goodsEntity.getSkuId());
                    settleItemList.add(map);
                }
            }
            OrderDetailsActivity.Companion.self(getActivity(), (int) selectCatShop.getId(), new Gson().toJson(settleItemList));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addCatEvent(CatRefreshEvent loginEvent) {
        getCatList();
    }

    @Override
    protected boolean isBindEventBus() {
        return true;
    }
}
